<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      border
      :height="600"
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import { getDevicelist } from "@/api/sensingEquipment/index.js";
import { dealElectricity, saveQuery, outQuery } from "@/utils/index";
import { typeAndLabelLv2Code } from "@/api/system/dict/data";

import operate from "@/views/resource/sensingEquipment/water/components/operate.vue";
import exports from "@/views/resource/sensingEquipment/water/components/exports.vue";
export default {
  name: "",
  components: {
    operate,
    exports,
  },
  dicts: ["subentry_type", "device_model", "wmeter_device_model"],
  data() {
    return {
      fromRouter: "",
      //弹窗
      id: "",
      modelName: "",
      show: false,
      live2Codes: [],
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            model: {
              label: "设备型号:",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.wmeter_device_model.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().model;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择设备型号",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("model", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            name: {
              label: "设备名称:",
              typeName: "el-input",
              placeholder: "请输入设备名称",
            },
            code: {
              label: "设备编码:",
              typeName: "el-input",
              placeholder: "请输入设备编码",
            },
            cardNum: {
              label: "物联网卡号:",
              typeName: "el-input",
              placeholder: "请输入物联网卡号",
            },
            status: {
              label: "设备状态:",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = [
                  {
                    value: 3,
                    label: "返厂",
                  },
                  {
                    value: 2,
                    label: "故障",
                  },
                  {
                    value: 1,
                    label: "启用",
                  },
                  {
                    value: 0,
                    label: "未启用",
                  },
                ];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().status;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择设备状态",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("status", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            subentryType: {
              label: "分项类型:",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = [
                  {
                    value: 3,
                    label: "返厂",
                  },
                  {
                    value: 2,
                    label: "故障",
                  },
                  {
                    value: 1,
                    label: "启用",
                  },
                  {
                    value: 0,
                    label: "未启用",
                  },
                ];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().status;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择设备状态",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("status", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            // subentryType: {
            //   label: "分项类型:",
            //   render: (h) => {
            //     let that = this;
            //     let arr = [];
            //     arr = that.live2Codes;
            //     // that.dict?.type?.subentry_type.some((item) => {
            //     //   arr.push(item);
            //     // });
            //     // 数据严谨处理,处理后端数据异常情况
            //     let valNum = that.$refs?.form?.getFieldsValue().subentryType;
            //     let a = [
            //       h(
            //         "el-select",
            //         {
            //           attrs: {
            //             placeholder: "请选择分项类型",
            //             value: valNum,
            //             clearable: true,
            //           },
            //           props: ["value"],
            //           on: {
            //             change: (value) => {
            //               that.$refs?.form?.setFieldValue(
            //                 "subentryType",
            //                 value
            //               );
            //               that.$forceUpdate();
            //             },
            //           },
            //         },
            //         [
            //           arr.map((item) => {
            //             let { label, value } = item;
            //             return h("el-option", {
            //               props: {
            //                 label,
            //                 value: value,
            //                 key: value,
            //               },
            //             });
            //           }),
            //         ]
            //       ),
            //     ];
            //     return h("div", a);
            //   },
            // },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            // {
            //   label: "新增",
            //   type: "primary",
            //   typeName: "el-button",
            //   plain: true,
            //   size: "small",
            //   icon: "el-icon-plus",
            //   click: () => this.showModel("operate"),
            // },
            // {
            //   label: "导入",
            //   type: "success",
            //   typeName: "el-button",
            //   size: "small",
            //   icon: "el-icon-upload2",
            //   click: () => this.showModel("exports"),
            // },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            prop: "code",
            label: "设备编码",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "name",
            label: "设备名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "model",
            label: "设备型号",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.wmeter_device_model}
                    value={scope.row.model}
                  />
                </div>
              );
            },
          },
          {
            prop: "cardNum",
            label: "物联网卡号",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "installLocation",
            label: "安装位置",
            minWidth: 150,
            align: "center",
            showOverflowTooltip: true,
            // render: (h, params) => {
            //   let num = dealElectricity(params.row.ratedPower, 1, 0);
            //   return h("div", {}, num);
            // },
          },
          {
            prop: "totalPower",
            label: "累计水耗（吨）",
            minWidth: 100,
            align: "center",
            render: (h, params) => {
              let num = dealElectricity(params.row.totalPower, 1, 2);
              return h("div", {}, num);
            },
          },
          // {
          //   prop: "subentryType",
          //   label: "分项类型",
          //   align: "center",
          //   showOverflowTooltip: true,
          //   render: (h, scope) => {
          //     let that = this;
          //     let a;
          //     let subentryType = scope.row.subentryType;
          //     let num = 0;
          //     if (that.live2Codes.length > 0) {
          //       that.live2Codes.map((item) => {
          //         if (subentryType == item.value) {
          //           a = item.label;
          //         } else {
          //           num++;
          //         }
          //       });
          //       if (num == that.live2Codes.length) {
          //         a = "";
          //       }
          //     } else {
          //       a = "";
          //     }
          //     return <div>{a}</div>;
          //   },
          // },
          {
            prop: "statusName",
            label: "设备状态",
            minWidth: 100,
            align: "center",
            render: (h, scope) => {
              let a = "";
              let type;
              switch (scope.row.statusName) {
                case "未启用":
                  type = "info";
                  break;
                case "启用":
                  type = "";
                  break;
                case "故障":
                  type = "danger";
                  break;
                case "返厂":
                  type = "warning";
                  break;
                default:
                  type = "";
              }
              a = (
                <el-tag size="big" type={type}>
                  {scope.row.statusName}
                </el-tag>
              );
              return <div>{a}</div>;
            },
          },
          {
            label: "操作",
            width: 200,
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a, b, c;
              a = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  v-hasPermi={["device:archive:detail"]}
                  onClick={() => {
                    console.log(scope.row);
                    let obj = {
                      model: that.$refs?.form?.getFieldsValue().model,
                      name: that.$refs?.form?.getFieldsValue().name,
                      code: that.$refs?.form?.getFieldsValue().code,
                      cardNum: that.$refs?.form?.getFieldsValue().cardNum,
                      subentryType:
                        that.$refs?.form?.getFieldsValue().subentryType,
                    };
                    saveQuery("waterdetailsticssearchQuery", obj);
                    that.$router.push({
                      name: "waterDetail",
                      query: {
                        id: scope.row.id,
                      },
                    });
                  }}
                >
                  详情
                </el-button>
              );
              b = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                  v-hasPermi={["device:archive:back", "device:archive:edit"]}
                  onClick={() => {
                    that.showModel("operate", scope.row);
                  }}
                >
                  编辑
                </el-button>
              );
              c = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  v-hasPermi={["device:archive:remove"]}
                  onClick={() => {
                    that.handlerDelete(scope.row);
                  }}
                  class="text-danger"
                >
                  删除
                </el-button>
              );
              return (
                <div>
                  {a}
                  {b}
                </div>
              );
            },
          },
        ],
        data: [],
      },
    };
  },
  created() {
    this.getTypeAndLabelLv2Code();
    const needstatusName =
      this.$route.query && this.$route.query.needstatusName;
    if (needstatusName) {
      setTimeout(() => {
        this.$refs?.form?.setFieldValue("status", 2);
      }, 100);
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.handlerSearchDetail();
      }, 100);
    });
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromRouter = from?.path ?? "";
    });
  },
  methods: {
    getTypeAndLabelLv2Code() {
      this.live2Codes = [];
      let code = 33;
      if (code) {
        typeAndLabelLv2Code("subentry_type", code)
          .then((response) => {
            if (response.code === 700) {
              this.$message.warning(response.msg);
              return false;
            }
            let arr = response?.data ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                let obj = {
                  label: item?.dictLabel,
                  value: item?.dictValue,
                };
                this.live2Codes.push(obj);
              });
            }
            console.log(this.live2Codes, "live2Codes");
          })
          .catch((err) => {
            // this.$message.error("系统错误,请联系管理员!");
          });
      }
    },
    async initData(data) {
      let that = this;
      let query = {
        ...data,
      };
      query.type = 1; // 0 电表 1 水表
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await getDevicelist(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 搜索
    handlerSearchDetail() {
      let form = {
        ...outQuery("waterdetailsticssearchQuery", this.fromRouter, [
          "/resource/sensingEquipment/waterdetail",
        ]),
      };
      if (Object.keys(form).length > 0) {
        this.$refs?.form?.setFieldValue("model", form?.model ?? null);
        this.$refs?.form?.setFieldValue("name", form?.name ?? "");
        this.$refs?.form?.setFieldValue("code", form?.code ?? "");
        this.$refs?.form?.setFieldValue("cardNum", form?.cardNum ?? "");
        this.$refs?.form?.setFieldValue("status", form?.status ?? null);
        this.$refs?.form?.setFieldValue(
          "subentryType",
          form?.subentryType ?? null
        );
      }
      const { ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
      };
      this.initData(data);
    },
    // 重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    // 删除
    handlerDelete(row) {
      let that = this;
      let id = row.id;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.delectRequest(id);
        })
        .catch(() => {
          that.$message({
            message: "取消删除",
          });
        });
    },
    // 删除请求
    delectRequest(id) {},
    // 弹窗
    showModel(name, params) {
      this.modelName = name;
      this.id = params?.id || "";
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped></style>
